<template>
  <PageContainer title="咨询工单">
    <div class="author-container">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索作家笔名"
          clearable
          style="width: 300px;"
          prefix-icon="Search"
        />
      </div>
      <!-- 作家列表区域 -->
      <div class="author-list-section">
        <h2 class="section-title">负责作家（{{ filteredAuthors.length }}人）</h2>
        <el-row :gutter="20" v-if="filteredAuthors.length > 0">
          <el-col :span="8" v-for="author in filteredAuthors" :key="author.authorId">
            <div class="author-card" @click="goToChat(author)">
              <!-- 作家头像 -->
              <div class="author-avatar">
                <img :src="author.authorAvatar" alt="作家头像" />
              </div>
              <!-- 作家核心信息 -->
              <div class="author-info">
                <div class="author-base">
                  <h3 class="author-name">{{ author.penName }}</h3>
                  <span class="session-tag" :class="getSessionClass(author.sessionStatus)">
                    {{ formatSessionStatus(author.sessionStatus) }}
                  </span>
                </div>
                <!-- 最新消息 -->
                <p class="latest-msg">
                  {{ author.latestMsg.content.length > 15 ? author.latestMsg.content.slice(0,15) + '...' : author.latestMsg.content }}
                </p>
                <!-- 消息时间 + 未读提示 -->
                <div class="msg-footer">
                  <span class="msg-time">{{ formatTime(author.latestMsg.sendTime) }}</span>
                  <el-badge v-if="author.unreadCount > 0" :value="author.unreadCount" class="unread-badge" />
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-empty v-else-if="!loading" description="暂无负责的作家" />
      </div>
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-placeholder">
        <el-skeleton animation="wave" rows="5" />
      </div>
    </div>
  </PageContainer>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { getAuthorList } from '@/api/service';
import { ElMessage, ElBadge } from 'element-plus';
import { useRouter } from 'vue-router';
import PageContainer from '@/components/PageContainer.vue';
import { format } from 'date-fns'; // 需安装date-fns：npm install date-fns

const router = useRouter();

// 组件状态
const loading = ref(true);
const searchKeyword = ref('');
const authors = ref([]); // 原始作家列表

// 加载作家列表数据
const loadAuthors = async () => {
  try {
    const result = await getAuthorList();
    const resData = result.data;
    if (resData.code !== '0000') {
      throw new Error(resData.msg || '获取作家列表失败');
    }
    const authorList = resData.data?.authorList || [];
    if (!Array.isArray(authorList)) {
      throw new Error('接口返回数据格式异常');
    }
    authors.value = authorList;
  } catch (error) {
    ElMessage.error(error.message || '加载作家数据失败');
    console.error('Error:', error);
    authors.value = [];
  } finally {
    loading.value = false;
  }
};

// 搜索过滤逻辑
const filteredAuthors = computed(() => {
  if (!Array.isArray(authors.value)) return [];
  return authors.value.filter(author => 
    author.penName.includes(searchKeyword.value)
  ).sort((a, b) => new Date(b.latestMsg.sendTime) - new Date(a.latestMsg.sendTime)); // 最新消息在前
});

// 格式化会话状态（中文显示）
const formatSessionStatus = (status) => {
  const map = { active: '活跃', closed: '已关闭' };
  return map[status] || status;
};

// 会话状态样式映射
const getSessionClass = (status) => {
  return status === 'active' ? 'session-active' : 'session-closed';
};

// 格式化时间（示例：2024-05-20 14:30）
const formatTime = (time) => {
  return time ? format(new Date(time), 'yyyy-MM-dd HH:mm') : '暂无时间';
};

// 跳转到聊天页面（携带sessionId）
const goToChat = (author) => {
  router.push(`/admin/service/session/${author.sessionId}`);
};

// 页面挂载时加载数据
onMounted(() => {
  loadAuthors();
});
</script>

<style lang="scss" scoped>
.author-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 100%;
  padding: 0 16px;
}

.search-section {
  margin: 16px 0;
}

.author-list-section {
  flex: 1;
  overflow-y: auto;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: #333;
}

.author-card {
  cursor: pointer;
  display: flex;
  padding: 16px;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px rgba(0,0,0,0.08);
  transition: all 0.3s;
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
  }
}

.author-avatar {
  width: 52px;
  height: 52px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 14px;
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.author-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.author-base {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.author-name {
  font-size: 14px;
  font-weight: 500;
  margin: 0;
  color: #1989fa;
}

.session-tag {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #fff;
}

.session-active {
  background-color: #67c23a;
}

.session-closed {
  background-color: #909399;
}

.latest-msg {
  font-size: 13px;
  color: #666;
  margin: 0 0 8px 0;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.msg-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.msg-time {
  font-size: 12px;
  color: #999;
}

.unread-badge {
  background-color: #f56c6c; // 保留红色主色
  color: #fff;
  font-size: 11px;
  height: 18px;
  width: 18px; // 改成正圆
  line-height: 18px;
  text-align: center;
  padding: 0; // 去掉内边距
  border-radius: 50%;
  border: 2px solid #fff; // 加白色边框，和卡片背景区分开
  // 删掉之前的box-shadow和伪元素
}

.loading-placeholder {
  padding: 40px 0;
  text-align: center;
  color: #909399;
}
</style>